package middleware

import (
	"admin-nexus-backend/config"
	"strconv"

	"github.com/gin-gonic/gin"
)

// CORS 跨域中间件
func CORS() gin.HandlerFunc {
	return func(c *gin.Context) {
		cors := config.GlobalConfig.CORS

		// 处理跨域请求的Origin头
		origin := c.Request.Header.Get("Origin")
		// 检查origin是否在允许列表中
		allowed := false
		for _, allowOrigin := range cors.AllowOrigins {
			if allowOrigin == "*" || allowOrigin == origin {
				allowed = true
				break
			}
		}

		// 如果origin在允许列表中，设置对应的响应头
		if allowed {
			c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
		} else if len(cors.AllowOrigins) > 0 && cors.AllowOrigins[0] == "*" {
			// 如果配置了*，允许所有来源
			c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		}

		if len(cors.AllowMethods) > 0 {
			methods := ""
			for i, method := range cors.AllowMethods {
				if i > 0 {
					methods += ", "
				}
				methods += method
			}
			c.Writer.Header().Set("Access-Control-Allow-Methods", methods)
		}

		if len(cors.AllowHeaders) > 0 {
			headers := ""
			for i, header := range cors.AllowHeaders {
				if i > 0 {
					headers += ", "
				}
				headers += header
			}
			c.Writer.Header().Set("Access-Control-Allow-Headers", headers)
		}

		if len(cors.ExposeHeaders) > 0 {
			headers := ""
			for i, header := range cors.ExposeHeaders {
				if i > 0 {
					headers += ", "
				}
				headers += header
			}
			c.Writer.Header().Set("Access-Control-Expose-Headers", headers)
		}

		if cors.AllowCredentials {
			c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		}

		if cors.MaxAge > 0 {
			c.Writer.Header().Set("Access-Control-Max-Age", strconv.Itoa(cors.MaxAge))
		}

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}
